﻿using System.Collections.Generic;
using System.Web.Script.Serialization;
using Wisdom.Core;

namespace Wisdom.Web.Mvc
{
    /// <summary>
    /// Defines an static class which contains extension methods of <see cref="object"/>.
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// Convert the given object into json string.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        public static string ToJson(this object instance)
        {
            return ToJson(instance, null);
        }

        /// <summary>
        /// Convert the given object into json string.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="jsonConverters">The json converters.</param>
        /// <returns></returns>
        public static string ToJson(this object instance, IEnumerable<JavaScriptConverter> jsonConverters)
        {
            Guard.IsNotNull(instance, "instance");

            var jsonSerializer = new JavaScriptSerializer();

            jsonSerializer.RegisterConverters(jsonConverters ?? new JavaScriptConverter[0]);

            return jsonSerializer.Serialize(instance);
        }
    }
}